import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import {
  ProCard,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
  ActionType,
  ProColumns,
} from '@ant-design/pro-components';
import { Button, message, Modal, Steps, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { completeComplaint, getComplaintDetail, queryNegotiations } from '../service';
import { ComplaintTableItem, NegotiationTableItem } from '../types.d';
import { mapOperateType } from '../utils';
import ReplayUser from '../components/ReplayUser';
import { useHistory } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import CheckRefund from '../components/CheckRefund';
import LoadInfo from '@/components/LoadInfo';

const EnhancedTag = (props: { state: string }) => {
  switch (props.state) {
    case 'PENDING':
      return (
        <Tag icon={<ClockCircleOutlined />} color="warning">
          待处理
        </Tag>
      );
    case 'PROCESSED':
      return (
        <Tag icon={<CheckCircleOutlined />} color="success">
          已处理完成
        </Tag>
      );
    default:
      return (
        <Tag icon={<SyncOutlined spin />} color="processing">
          处理中
        </Tag>
      );
  }
};
const mapHandleStatus = (state: string) => {
  switch (state) {
    case 'Processing':
      return 'process';
    case 'PROCESSED':
      return 'finish';
    default:
      return 'wait';
  }
};
const { Step } = Steps;
const Detail = () => {
  // const { citem } = props;
  const history = useHistory<string>();
  const [replayVisible, setReplayVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [detailItem, setDetailItem] = useState<ComplaintTableItem | null>(null);
  const ref = useRef<ActionType>();
  useEffect(() => {
    if (history.location.state) {
      setLoading(true);
      getComplaintDetail(history.location.state).then((res) => {
        if (res.success) {
          setDetailItem(res.data);
        } else {
          message.error({ content: res.message || '获取失败', key: 'complaint_detail' });
          setDetailItem(null);
        }
        setLoading(false);
      });
    }
  }, []);
  const detailColumns: ProDescriptionsItemProps<ComplaintTableItem>[] = [
    {
      title: '投诉单号',
      dataIndex: 'complaintId',
    },
    {
      title: '投诉时间',
      dataIndex: 'complaintTime',
      valueType: 'dateTime',
    },
    {
      title: '问题类型',
      dataIndex: 'problemType',
      valueEnum: {
        REFUND: { text: '申请退款', status: 'Error' },
        SERVICE_NOT_WORK: { text: '服务权益未生效', status: 'Error' },
        OTHERS: {
          text: '其他类型',
          status: 'Error',
        },
      },
    },
    {
      title: '问题描述',
      dataIndex: 'problemDesc',
    },
    {
      title: '申请退款金额(元)',
      dataIndex: 'applyRefundAmount',
      fieldProps: {
        moneySymbol: false,
      },
      renderText: (text) => (text ? (text / 100).toFixed(2) : '-'),
    },
    {
      title: '用户投诉次数',
      dataIndex: 'complaintTimes',
      valueType: 'digit',
    },
    {
      title: '支付金额(元)',
      dataIndex: 'orderInfos',
      valueType: 'money',
      fieldProps: {
        moneySymbol: false,
      },
      renderText: (_, record) => {
        if (!record.orderInfos || record.orderInfos.length < 1) return '-';
        return (Number(record.orderInfos[0].amount) / 100).toFixed(2);
      },
    },
    {
      title: '被诉商户号',
      dataIndex: 'mchid',
    },
    {
      title: '微信支付订单号',
      dataIndex: 'orderInfos',
      renderText: (_, record) => {
        if (!record.orderInfos || record.orderInfos.length < 1) return '暂无数据';
        return record.orderInfos[0].payOrderNo;
      },
    },
    {
      title: '投诉人联系方式',
      dataIndex: 'phone',
    },
    {
      title: '平台支付号',
      dataIndex: 'orderInfos',
      renderText: (_, record) => {
        if (!record.orderInfos || record.orderInfos.length < 1) return '暂无数据';
        return record.orderInfos[0].payNo;
      },
    },
    {
      title: '投诉人openid',
      dataIndex: 'openId',
    },
  ];
  const historyColumns: ProColumns<NegotiationTableItem>[] = [
    {
      title: '时间',
      dataIndex: 'operateTime',
      align: 'center',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '角色',
      dataIndex: 'operator',
      align: 'center',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '动作类型',
      dataIndex: 'operateType',
      align: 'center',
      hideInSearch: true,
      hideInForm: true,
      renderText: (text) => mapOperateType(text),
    },
    {
      title: '内容',
      dataIndex: 'operateDetails',
      hideInSearch: true,
      hideInForm: true,
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        breadcrumb: {},
        title: '',
      }}
    >
      {detailItem ? (
        <ProCard
          direction="column"
          title={
            <>
              投诉单号：{detailItem.complaintId} <EnhancedTag state={detailItem.state} />
            </>
          }
          extra={
            <a style={{ fontWeight: 'bold', fontSize: '16px' }} onClick={() => history.goBack()}>
              &lt; 返回投诉列表
            </a>
          }
        >
          <ProCard title="详情信息">
            <ProDescriptions column={2} columns={detailColumns} dataSource={detailItem} />
          </ProCard>
          <ProCard
            title="投诉进展"
            extra={
              <>
                {/* {!detailItem.fullRefunded && <Button>退款</Button>} */}
                {!detailItem.fullRefunded && detailItem.problemType == 'REFUND' && (
                  <CheckRefund
                    complaintId={detailItem.complaintId}
                    close={(newItem?: ComplaintTableItem) => {
                      if (newItem) {
                        setDetailItem(newItem);
                        ref.current?.reload();
                      }
                    }}
                  />
                )}
                <Button
                  key="replay-user"
                  type="primary"
                  style={{ marginLeft: '5px' }}
                  onClick={() => {
                    setReplayVisible(true);
                  }}
                >
                  回复用户
                </Button>
                {/* TODO:未处理的投诉单也不可以完成 */}
                <Button
                  disabled={detailItem.state != 'PROCESSING'}
                  key="complete-c"
                  style={{ marginLeft: '5px' }}
                  onClick={() => {
                    Modal.confirm({
                      title: '完成确认',
                      icon: <ExclamationOutlined />,
                      content: (
                        <div>
                          <div>是否确认要完成当前投诉单?</div>
                          <div style={{ fontWeight: 'bold', color: 'red' }}>
                            请务必在真实处理完用户投诉后再进行此项操作，避免因投诉未妥善处理造成用户重复投诉。
                          </div>
                        </div>
                      ),
                      onOk: async () => {
                        message.loading({ key: 'complete-c', content: '正在处理，请稍后...' });
                        const res = await completeComplaint(detailItem.complaintId);
                        if (res.success) {
                          message.success({
                            content: res.message,
                            key: 'complete-c',
                          });
                          setDetailItem(res.data);
                          return true;
                        }
                        message.error({ content: res.message, key: 'complete-c' });
                        return false;
                      },
                    });
                  }}
                >
                  处理完成
                </Button>
              </>
            }
          >
            <Steps progressDot style={{ paddingTop: '50px' }} labelPlacement="vertical">
              <Step status="finish" title="用户发起投诉" />
              <Step status={detailItem.state == 'PENDING' ? 'process' : 'finish'} title="待处理" />
              <Step status={mapHandleStatus(detailItem.state)} title="处理中" />
              <Step
                status={detailItem.state == 'PROCESSED' ? 'finish' : 'wait'}
                title="已处理完成"
              />
            </Steps>
          </ProCard>
          <ProCard title="协商历史">
            <ProTable<NegotiationTableItem>
              columns={historyColumns}
              search={false}
              rowKey="logId"
              columnEmptyText="暂无数据"
              size="small"
              options={false}
              actionRef={ref}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 10,
                size: 'small',
              }}
              debounceTime={300}
              request={async (param) => {
                const res = await queryNegotiations(detailItem.complaintId, param);
                return res;
              }}
            />
          </ProCard>
          {replayVisible && (
            <ReplayUser
              complaintId={detailItem.complaintId}
              visible={replayVisible}
              close={(newItem?: ComplaintTableItem) => {
                if (newItem) {
                  setDetailItem(newItem);
                  ref.current?.reload();
                }
                setReplayVisible(false);
              }}
            />
          )}
        </ProCard>
      ) : (
        // <ProCard>
        //   {mapInfoCpu(loading, () => {
        //     history.goBack();
        //   })}
        // </ProCard>
        <LoadInfo
          loading={loading}
          action={() => {
            history.goBack();
          }}
          actionText={<>&lt; 返回投诉列表</>}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default Detail;
